import house from './template/house.vue';
import mintPicker from '@/pages/reservation/template/mintPicker.vue';
// import calendar from './calendar/calendar.vue';
// import rentTime from '@/pages/shortHouselist/template/rentTime/rentDate.vue';
import { Toast,MessageBox  } from 'mint-ui';
import MoUpload from '@/components/upload.vue';
import {mapMutations,mapState} from 'Vuex';
import {mobileTest,reLoginWX,trim} from '@/util/util.js';
export default {
  name: "",
  data: () => ({
    houseInfo:'',
    houseHeaderImg:'',    //房源图片，获取图片列表的第一张
    name:'',
    startDate:'',
    leaveDate:'',
    sex:1,
    switchLeft:'left',
    idCard:'',
    mobile:'',
    yzmCode:'',
    isMintPicker:false,
    idCardPic1: '',   //身份证正面img
    idCardPic2: '',  //身份证背面img
    showCalendar:false,   //显示日历
    datetips:0,     //0：开始时间；1：结束时间
    difMobile:false,    //手机号码输入与用户本身号码不一致 验证码开关，true为需要验证
    isGetYzmTime:false,   //倒计时内不能重复点击获取验证码
    yzmTime:60,
    trainDateFullList:[],
    inviteMobile:'',
  }),
  components: {
    house,
    mintPicker,
    MoUpload,
    // calendar,
    rentTime:()=>import('./calendar/rentDate.vue'),
  },
  mounted() {
    //do something after mounting vue instance
    let that = this;
    let houseId = that.$route.query.houseId;
    let userInfo_storage = JSON.parse(window.localStorage.getItem('userInfo'));

    let inviteMobile = window.localStorage.getItem('inviteMobile');   //推荐者电话号码
    console.log(inviteMobile);
    this.inviteMobile = inviteMobile?inviteMobile:'';

    that.mobile = that.userInfo.mobile? that.userInfo.mobile : userInfo_storage.mobile;
    network.get(configUrl.HOUSEDETAIL_URL,{houseId:houseId},function(res){
      console.log(res);
      that.houseInfo = res.data.house;
      that.houseHeaderImg = res.data.housePicList[0];

      if (res.data.house.rentType==2) {
        // 短租房源已租列表
        network.get(configUrl.SHORTRENTHOUSEFREEDATE_URL,{
          houseId:houseId,
          startDate:'',
          months:4,
        },function (res) {
          console.log(res);
          // that.trainDateFullList = res.dataList;
          let trainDateList = [];
          let allDateList = [];
          let dataList = res.dataList;    //所有已租时间段数组
          for (let i = 0; i < dataList.length; i++) {
            let dayNum = dataList[i].dayNum;    //每个时间段有几天
            let startDay = dataList[i].startDay;  //每个时间段的入住时间
            let daySplit = startDay.split('-');
            trainDateList[i] = daySplit[0]+daySplit[1]+daySplit[2];
            allDateList[i] = [];
            for (var j = 0; j < dayNum; j++) {
              allDateList[i][j] = parseFloat(trainDateList[i])+j;
            }
          }

          let trainDateFullList = [];
          for (var i = 0; i < allDateList.length; i++) {
            trainDateFullList = trainDateFullList.concat(allDateList[i]);
          }
          console.log([...new Set(trainDateFullList)]);//数组去重
          that.trainDateFullList = ''+[...new Set(trainDateFullList)];
          that.setRentDateList(''+[...new Set(trainDateFullList)]);
        },function (msg) {
          console.log(msg);
        })
      }
    },function(err){
      console.log(err);
    });

    if(that.signContact!=''){
      console.log('已填写过信息');
      that.name = that.signContact.rentUserName;
      that.startDate = that.signContact.startDate;
      that.leaveDate = that.signContact.leaveDate;
      that.sex = that.signContact.sex;
      that.idCard = that.signContact.idCard;
      that.mobile = that.signContact.mobile;
      that.idCardPic1 = that.signContact.idCardPic1;
      that.idCardPic2 = that.signContact.idCardPic2;
      that.mobile = that.signContact.mobile;
    }
  },
  computed: {
    ...mapState({
      signContact:state=>state.contact.signForm,
      userInfo:state=>state.login.userInfo,
      rentDateList:state=>state.contact.rentDateList,
    })
  },
  methods: {
    ...mapMutations([
      'setSignForm',
      'setUserInfo',
      'setsignCalendar',
      'setRentDateList',
    ]),
    addPreZero(num){//小于9的需要添加0前缀
        return (num>9) ? num:('0'+num);
    },
    rentTimeEvent(data) {
      console.log(data);
      this.showCalendar = false;
      let startDate = data.startTime;   //入住时间
      let endDate = data.endTime;       //离开时间
      if (startDate=='') {    //未选择入住时间，默认为今天的日期
        let todayDate = new Date();
        let year = todayDate.getFullYear();
        let month = this.addPreZero(todayDate.getMonth()+1);
        let date = this.addPreZero(todayDate.getDate());
        this.startDate = year+'-'+month+'-'+date;
      }else {
        this.startDate = startDate.year+'-'+startDate.month+'-'+startDate.date;
      }
      if (endDate=='') {
        this.leaveDate = '';
      }else {
        this.leaveDate = endDate.year+'-'+endDate.month+'-'+endDate.date;
      }


    },
    // 选择性别
    switchSex() {
      let that = this;
      let sex = that.sex;
      if(sex==1){
        that.switchLeft = 'right';
        that.sex = 0;
      }else{
        that.switchLeft = 'left';
        that.sex = 1;
      }
    },

    mintPickerBtn(data) {
      let that = this;
      that.isMintPicker = false;
    },
    chooseStartdate() {
      this.showCalendar = true;
      this.datetips = 0;
    },
    chooseEnddate() {
      this.showCalendar = true;
      this.datetips = 1;
    },

    // 七牛图片上传处理
    uploadComplete(status, result, uploadResult, flag) {
       // var addr = 'http://opf2ucy0n.bkt.clouddn.com/';
      //  console.log(uploadResult);
      // console.log(result);
        if (status == 200) { //
            this.idCardPic1 = uploadResult.link+'/'+result.key //七牛域名 + 返回的key 组成文件url
        } else {
            //失败处理
        }
    },
    uploadComplete2(status, result, uploadResult, flag) {
       // var addr = 'http://opf2ucy0n.bkt.clouddn.com/';
      //  console.log(uploadResult);
      // console.log(result);
        if (status == 200) { //
            this.idCardPic2 = uploadResult.link+'/'+result.key //七牛域名 + 返回的key 组成文件url
        } else {
            //失败处理
        }
    },
    iptMobile() {
      console.log(this.mobile);
      let that = this;
      let mobile = that.mobile;
      if(mobile.length==11 && (that.userInfo.mobile != '') ){
        console.log('号码输入结束');
        if(mobile != that.userInfo.mobile) {
          that.difMobile = true;
        }
      }
    },
    // 获取验证码
    getYzm() {
      let that = this;
      let mobile = that.mobile;
      console.log(mobile);
      let yzmParam = {
        mobile:trim(mobile),
        pinType:4     //验证码类型 1 注册登录 2在线委托 3合同签约 4手机号换绑 5修改智能门锁密码 6预约看房
      };

      network.get(configUrl.LOGINGETYZM_URL,yzmParam,function(res){
        console.log(res);
        Toast('验证码发送成功');
        that.yzmTime = 60;
        that.isGetYzmTime = true;

        let yzmInterval = setInterval(()=>{
          that.yzmTime --;
          if(that.yzmTime==0){
            that.isGetYzmTime = false;
            return false;
          }
        },1000);
      },function(err){
        console.log(err);
      });
    },
    // 提交签约
    submitSignContact() {
      let that = this;
      let rentUserName = that.name;
      let idCard = that.idCard;
      // IDCard:
      // [/^[1-9]\d{5}[1-9]\d{3}(((0[13578]|1[02])(0[1-9]|[12]\d|3[0-1]))|((0[469]|11)(0[1-9]|[12]\d|30))|(02(0[1-9]|[12]\d)))(\d{4}|\d{3}[xX])$/,"身份证错误"],
      if(idCard==''){
        Toast('请输入身份证号码');
        return false;
      }else {
        let IDCardreg = /^[1-9]\d{5}[1-9]\d{3}(((0[13578]|1[02])(0[1-9]|[12]\d|3[0-1]))|((0[469]|11)(0[1-9]|[12]\d|30))|(02(0[1-9]|[12]\d)))(\d{4}|\d{3}[xX])$/
        if(IDCardreg.test(idCard)==false){
          Toast('身份证号码格式错误');
          return false;
        }
      }
      if(rentUserName==''){
        Toast('请填写姓名');
        return false;
      }
      let mobile = that.mobile;
      if(mobile==''){
        Toast('请填写联系电话');
        return false;
      }
      if(mobileTest(mobile)){
        console.log('手机号码输入有误');
        return false;
      }
      let startDate = that.startDate; //入住时间
      let leaveDate = that.leaveDate; //离开时间
      if (that.houseInfo.rentType==2) {   //短租签约
        if (startDate=='' || leaveDate=='') {
          Toast('请选择入住时间或者离开时间');
          return false;
        }
      }

      let idCardPic1 = that.idCardPic1;
      if(idCardPic1==''){
        Toast('请选择身份证正面照');
        return false;
      }
      let idCardPic2 = that.idCardPic2;
      if(idCardPic2==''){
        Toast('请选择身份证反面照');
        return false;
      }
      let yzmCode = that.yzmCode;
      if(that.difMobile){
        if(yzmCode==''){
          Toast('请输入验证码');
          return false;
        }
      }

      let signParam = {
        houseId:that.houseInfo.houseId,
        inviteMobile:that.inviteMobile,      //邀请人手机
        rentUserName:rentUserName,      //姓名
        sex:that.sex,      //性别
        idCard:idCard,      //身份证号码
        idCardPic1:idCardPic1,    //身份证正面
        idCardPic2:idCardPic2,    //身份证反面
        startDate:that.startDate,      //入住日期
        leaveDate:that.leaveDate,      //离开日期
        mobile:mobile,            //联系电话
        yzmCode:yzmCode,     //验证码
      }
      that.setSignForm(signParam);    //将form表单填写好的数据放入store数据仓库里面
      network.post(configUrl.SIGNCONTACT_URL,signParam,function(res){
        console.log(res);
        if(res.code==401) {
          reLoginWX();
        }else{
          let billContact = res.data;   //billId,contractId字段
          MessageBox.alert('签约提交成功').then(active=>{
            that.$router.push({
              path:'/billDetail',
              query:{billId:billContact.billId,contractId:billContact.contractId}
            });
          });
        }
      },function(err){
        console.log(err);
      });
    }
  },
  beforeRouteLeave(to,from,next) {
    window.localStorage.removeItem('inviteMobile');   //删除对应缓存
    next();
  }
}
